// 创建axios实例
import axios from "axios";
import { useTokenStore } from "@/stores/userTokenStore";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter();
// const router = window.appContext.config.globalProperties.$router;
const baseURL = "/api";
const instance = axios.create({ baseURL });

// 添加请求拦截器
instance.interceptors.request.use(
  (config) => {
    //请求前的回调
    const tokenStore = useTokenStore();
    //判断有没有token
    if (tokenStore.token) {
      config.headers.Authorization = tokenStore.token; // 添加token到请求头
    }
    return config; // 返回修改后的请求配置
  },
  (err) => {
    //请求错误的回调
    return Promise.reject(err); // 处理错误
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  (result) => {
    //判断业务状态码
    if (result.data.code === 0) {
      return result.data;
    } else {
      ElMessage({
        message: result.data.message,
        type: "warning",
      });
    }
    return Promise.reject(result.data);
  },
  (err) => {
    //判断响应状态码,如果为401,则证明未登录,提示请登录,并跳转到登录页面
    if (err.response.status === 401) {
      ElMessage.error("请先登录");
      router.push("/login");
    } else {
      ElMessage.error("服务异常");
    }

    return Promise.reject(err); //异步的状态转化成失败的状态
  }
);

export default instance;
